const app = getApp()
Page({
  data: {
    cardAndFaceList: [],
    addCard: {
      show: false,
      list: {}
    },
    editCard: {
      show: false,
      list: {}
    },
    addFace: {
      show: false,
      step: 0, // 步骤 0 输入使用人阶段 1拍照阶段 2拍照结束阶段
      src: '',
      member_room_id: '',
      shoot: false, // 拍照状态 是否同意
      remark: '',//使用人
    },
    timing: null, //定时
    showLoading: true, //查询loading
  },
  onLoad() {
    this.getCardAndFaceList();
  },
  // 页面卸载
  onUnload() {
    console.log('页面卸载了');
    // 关闭定时器
    clearTimeout(this.data.timing);
  },
  // copy字符串
  copyString(e) {
    let str = e.currentTarget.dataset.str;
    wx.setClipboardData({
      data: str,
    })
  },
  // 定时查询  根据当前列表有没有查询中或者同步中 有的话 就1.5秒去查询一次  不要在开发者工具中快速刷新页面 不然容易无法触发页面卸载导致没有关闭定时器 重复查询
  timingSearch() {
    clearTimeout(this.data.timing); //清除之前的定时器 避免重复getCardAndFaceList执行 出现多个定时器
    let list = this.data.cardAndFaceList,
      flag = 0; // 标识 0 不查询 1查询   根据是否有设备是查询中或者同步中
    // 查询标识
    list.map(item => {
      item.member_room_card.map(item2 => {
        for (let i in item2.status_content) {
          let item3 = item2.status_content[i];
          if ([0, 3].includes(item3.status)) flag = 1;
        }
      })
    })
    if (flag) {
      this.setData({ showLoading: false }) //关闭loading

      let timing = setTimeout(() => {
        this.getCardAndFaceList()
      }, 1500);
      this.setData({ timing })
    } else {
      console.log('没有找到查询中或者同步中,不需要定时查询');
    }
  },
  // 获取卡片和人脸列表
  getCardAndFaceList() {
    app.call.request('wxapp/getCardAndFaceList', {}, (res) => {
      let data = res.data;

      // 设备状态默认未知  0未知 1未绑定 2已绑定
      data.map(item => {
        item.member_room_card.map(item2 => {
          item2.elevator_list.map(item3 => {
            if (item2.type == 1) item3.cardState = 0; // 卡号
            if (item2.type == 2) item3.faceState = 0; // 人脸
          })
        })
      })

      // 区分卡号和人脸 用于分类筛选
      data.map(item => {
        item.roomCardList = [];  // 卡片列表
        item.roomFaceList = [];  // 人脸列表
        item.member_room_card.map(item2 => {
          if (item2.type == 1) item.roomCardList.push(item2);
          if (item2.type == 2) item.roomFaceList.push(item2);
        })
      })

      // 给每一个房号中每个卡片或者人脸中的每一台设备绑定状态  
      // item 房号 item2 卡片或者人脸  item3 设备
      data.map(item => {
        item.member_room_card.map(item2 => {
          item2.elevator_list.map(item3 => {
            // 获取当前卡片或者人脸在当前设备下的状态 status -1未同步 0是同步中  1是成功 2是失败  3是查询中  select_time 时间戳
            let status = item2.status_content[item3.deviceSn];
            if (status) item3.deviceState = status;
            // 当status_content为空 表示未同步 用于解决老的数据之后新增设备 导致为空的问题
            else item3.deviceState = { status: -1 }

          })
        })
      })

      // 设置查询失败状态  
      // item 房号 item2 卡片或者人脸  item3 设备
      data.map(item => {
        item.member_room_card.map(item2 => {
          item2.elevator_list.map(item3 => {
            // 状态 status  -1未同步 0是同步中  1是成功 2是失败  3是查询中  select_time 时间戳/秒
            if (item3.deviceState && item3.deviceState.status == 3) {
              let nowTime = new Date().getTime() / 1000; //秒
              //  如果当前时间已经超过查询时间 300秒 也就是5分钟    则显示查询失败 
              if (item3.deviceState.select_time && (nowTime - item3.deviceState.select_time) > 300) {
                item3.deviceState.status = 4; //查询失败
              }
            }
          })
        })
      })

      // 是否显示一键查询和一键修复
      data.map(item => {
        item.showOncKey = false;
        if (item.member_room_card.length) item.showOncKey = true;
      })

      // 缩短人脸的key
      data.map(item => {
        item.member_room_card.map(item2 => {
          if (item2.face_key) item2.face_key_short = item2.face_key.substring(0, 10) + '...'
        })
      })

      // 是否显示 “添加卡号、添加照片、分享照片” 条件为 在有效期内+有剩余卡槽
      data.map(item => {
        item.isShowAddCardFaceShare = true;
        if (new Date().getTime() / 1000 > item.room.serve_end_time || (item.room.card_num - item.room_card_face_number <= 0)) {
          item.isShowAddCardFaceShare = false;
        }
      })

      this.setData({ cardAndFaceList: data })

      this.timingSearch();
    }, '', this.data.showLoading)
  },
  // 解绑房号
  unbindRoom(e) {
    wx.showModal({
      title: '温馨提示',
      content: '是否解除该房号的绑定，解除后将删除该房号下所有卡号并且不再绑定该房号',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          let data = { member_room_id: e.currentTarget.dataset.id }
          app.call.request('wxapp/delUserRoom', data, () => {
            app.showTip('解绑成功');
            this.getCardAndFaceList();
          })
        }
      }
    })
  },
  // 打开添加卡号
  openAddCard(e) {
    if (e.currentTarget.dataset.isshowaddcardfaceshare == false) {
      app.showTip('已过期或卡槽已满');
      return;
    }

    this.setData({ 'addCard.show': true, 'addCard.list': { card_number: '', remark: '', member_room_id: '' } })
    this.data.addCard.list.member_room_id = e.currentTarget.dataset.id;

    // 全屏滚动 hidden 禁止滚动 auto 恢复滚动
    wx.setPageStyle({ style: { overflow: 'hidden' } })
  },
  // 关闭添加卡号
  closeAddCard() {
    this.setData({ 'addCard.show': false })

    // 全屏滚动 hidden 禁止滚动 auto 恢复滚动
    wx.setPageStyle({ style: { overflow: 'auto' } })
  },
  // 监听添加卡号表单输入框改变
  addCardListChange(e) {
    let value = e.detail.value,
      field = e.currentTarget.dataset.type;
    this.setData({ [`addCard.list.${field}`]: value });
  },
  // 添加卡号
  addCard() {
    let data = this.data.addCard.list;
    if ([10, 16, 19].includes(data.card_number.length) == false) {
      app.showTip('卡号错误,目前支持10位、16位、19位');
    } else if (data.remark == '') {
      app.showTip('使用人不能为空');
    } else if (data.remark.length > 10) {
      app.showTip('使用人不能超过十个字符');
    } else {
      wx.showModal({
        title: '提示',
        content: '确认绑定卡号吗?',
        success: (res) => {
          if (res.confirm) {
            let postData = {
              member_room_id: data.member_room_id,
              card_number: data.card_number,
              remark: data.remark,
            };
            app.call.request('wxapp/bindCard', postData, (res) => {
              this.closeAddCard();
              app.showTip('绑定成功');
              setTimeout(() => {
                this.getCardAndFaceList();
              }, 700);
            })
          }

        },
      })
    }
  },
  // 打开修改卡号
  openEditCard(e) {
    this.setData({ 'editCard.show': true, 'editCard.list': e.currentTarget.dataset.card })

    // 全屏滚动 hidden 禁止滚动 auto 恢复滚动
    wx.setPageStyle({ style: { overflow: 'hidden' } })
  },
  // 关闭修改卡号
  closeEditCard() {
    this.setData({ 'editCard.show': false })

    // 全屏滚动 hidden 禁止滚动 auto 恢复滚动
    wx.setPageStyle({ style: { overflow: 'auto' } })
  },
  // 监听修改卡号表单输入框改变
  editCardListChange(e) {
    let value = e.detail.value,
      field = e.currentTarget.dataset.type;
    this.setData({ [`editCard.list.${field}`]: value });
  },
  // 提交修改卡号
  editCard() {
    let data = this.data.editCard.list,
      postData = {
        member_room_card_id: data.id,
        remark: data.remark,
      }
    if (postData.remark == '') {
      app.showTip('使用人不能为空');
    } else if (postData.remark.length > 10) {
      app.showTip('使用人不能超过十个字符');
    } else {
      app.call.request('wxapp/editRemark', postData, (data) => {
        app.showTip('修改成功');
        this.closeEditCard();
        setTimeout(() => {
          this.getCardAndFaceList();
        }, 700);
      });
    }

  },
  // ----------------NFC自动读卡开始
  nfcOpen() {
    this.nfcRead()
  },
  //nfc
  nfcRead() {
    const nfc = wx.getNFCAdapter()
    let isoDep = nfc.getIsoDep()
    this.isoDep = isoDep
    let _this = this
    function discoverHandler(res) {
      console.log('discoverHandler', res)    // 发现者
      const data = new Uint8Array(res.id)
      let str = ""
      data.forEach(e => {
        let item = e.toString(16)
        if (item.length == 1) {
          item = '0' + item
        }
        item = item.toUpperCase()
        console.log(item)
        str += item
      })
      _this.setData({
        newCardCode: str
      })

      let {
        techs
      } = res
      if (techs.includes('ISO-DEP')) {
        _this.WriteNFC()
      } else {
        app.showTip('该设备不支持ISO-DEP标准')
      }
      return _this.data.newCardCode
    }

    //NFC
    nfc.startDiscovery({
      success(res) {
        console.log(res)
        app.showTip('NFC读取功能已开启！请讲羊城通卡置于手机NFC读取处读取')
        nfc.onDiscovered(discoverHandler)
      },
      fail(err) {
        console.log('failed to discover:', err)
        if (!err.errCode) {
          app.showTip('请检查NFC功能是否正常!')
          return
        }
        switch (err.errCode) {
          case 13000:
            app.showTip('设备不支持NFC!')
            break;
          case 13001:
            app.showTip('系统NFC开关未打开!')
            break;
          case 13019:
            app.showTip('用户未授权!');
            break;
          case 13010:
            app.showTip('未知错误!');
            break;
        }
      }
    })
  },
  async WriteNFC(x, y) {
    let that = this
    console.log('调用命令')
    await this.connect()
  },
  // 连接
  connect() {
    let that = this
    console.log('连接')
    this.isoDep.connect({
      success: res => {
        that.getHistoricalBytes()
      },
      fail: error => {
        console.log(error)
        return
      }
    })
  },
  async getHistoricalBytes() {
    let that = this
    console.log('复位')
    this.isoDep.getHistoricalBytes({
      success: res => {
        that.instructionsList()
      },
      fail: error => {
        console.log(error)
        return
      }
    })
  },

  async instructionsList() {
    // 发送的指令集合，根据具体要求写
    await this.transceiveFunc('00A404000E315041592E5359532E4444463031')
    await this.transceiveFunc('00A40400085041592E41505059')
    await this.transceiveFunc('00B095001E')
  },

  transceiveFunc(instructions) {
    let that = this
    const sendData = new Uint8Array(instructions.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    return new Promise((resolve, rejected) => {
      this.isoDep.transceive({
        data: sendData.buffer,
        success: res => {
          console.log('传输成功')
          let resbuf = res.data
          let str = that.ab2str(resbuf)
          console.log(resbuf)
          console.log(str)
          var code = that.subStringMulti(str, 'ffffffffffffffff', 'ffffffff');
          if (code.length > 0) {
            app.showTip('读取成功')
            code[0] = code[0].substring(0, 16)
          } else {
            app.showTip('读取失败')
          }

          // 设置卡号
          that.setData({ 'addCard.list.card_number': code[0] })
          resolve()
        },
        fail: error => {
          console.log(error)
          rejected('错误')
        }
      })
    })
  },
  ab2str(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice((-2))
      })
    return hexArr.join('')
  },
  subStringMulti(text, begin, end) {
    var regex;
    if (end == '\\n')
      regex = new RegExp(begin + '(.+)', "g");
    else
      regex = new RegExp(begin + '([\\s\\S]+?)' + end, "g");
    try {
      var result;
      var blocks = [];
      while ((result = regex.exec(text)) != null) {
        blocks.push(result[1].trim());
      }
      return blocks;
      // return text.match(regex);
    } catch (err) {
      return null;
    }
  },
  // ----------------NFC自动读卡结束
  // 打开添加人脸
  openAddFace(e) {

    if (e.currentTarget.dataset.isshowaddcardfaceshare == false) {
      app.showTip('已过期或卡槽已满');
      return;
    }

    this.setData({ 'addFace.show': true, 'addFace.step': 0, 'addFace.src': '', 'addFace.shoot': false, 'addFace.remark': '' })
    this.data.addFace.member_room_id = e.currentTarget.dataset.id;
  },
  // 是否同意协议
  addFaceShootChange() {
    let state = this.data.addFace.shoot;
    this.setData({ 'addFace.shoot': !state })
  },
  // 拍照
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({ 'addFace.src': res.tempImagePath, 'addFace.step': 2 });
      }
    })
  },
  // 添加人脸使用人更新
  addFaceRemarkChange(e) {
    this.setData({ 'addFace.remark': e.detail.value })
  },
  // 去拍照阶段
  goAddFaceCamera() {
    this.setData({ 'addFace.step': 1 });
  },
  // 去添加使用人阶段
  goAddFaceRemark() {
    this.setData({ 'addFace.step': 0 });
  },
  // 重拍
  cameraRetake() {
    this.setData({ 'addFace.step': 1, 'addFace.src': '', });
  },
  // 上传人脸 
  uploadFace() {
    app.uploadFace(this.data.addFace.src, (src) => {
      let data = { member_room_id: this.data.addFace.member_room_id, face: src, remark: this.data.addFace.remark }
      app.call.request('wxapp/bindCard', data, (res) => {
        app.showTip('添加照片成功', 'none', () => {
          setTimeout(() => {
            this.setData({ 'addFace.show': false })
            this.getCardAndFaceList();
          }, 1000);
        });
      });
    });
  },
  // 删除卡号和人脸
  delCardFace(e) {
    let data = e.currentTarget.dataset.cardface;
    wx.showModal({
      title: '提示',
      content: data.type == 1 ? '是否删除此卡' : '是否删除此照片',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          let postData = { member_room_card_id: data.id, }
          app.call.request('wxapp/delCard', postData, (res) => {
            app.showTip('删除成功');
            setTimeout(() => {
              this.getCardAndFaceList();
            }, 500);
          })
        }
      }
    })
  },
  // 修改人脸备注
  editFaceRemark(e) {
    let cardFace = e.currentTarget.dataset.cardface;
    wx.showModal({
      title: '请输入使用人',
      content: cardFace.remark,
      editable: true,
      placeholderText: '请输入',
      success: (res) => {
        if (res.confirm) {
          let remark = res.content;
          if (remark == '') {
            app.showTip('使用人不能为空');
          } else if (remark.length > 10) {
            app.showTip('使用人不能超过十个字符');
          } else {
            app.call.request('wxapp/editMemberRoomFaceRemark', { remark, id: cardFace.id }, () => {
              app.showTip('修改成功');
              setTimeout(() => {
                this.getCardAndFaceList();
              }, 500);
            })
          }

        }
      }
    })
  },
  // 自主登记
  goRegister() {
    wx.navigateTo({ url: '/pages/register/register' });
  },
  // 添加异常上报
  addCardFaceAbnormal(e) {
    wx.showModal({
      title: '提示',
      content: '确认异常上报吗?',
      success: (res) => {
        if (res.confirm) {
          let item = e.currentTarget.dataset.item,
            cardface = e.currentTarget.dataset.cardface;
          // 设备序列编号
          let deviceSn = [];
          cardface.elevator_list.map(item => deviceSn.push(item.deviceSn));
          // 电梯绑定状态 - 卡号
          let cardState = [];
          if (cardface.type == 1) {
            cardface.elevator_list.map(item => {
              // 0是未同步到设备 1是同步成功 2是同步失败（同步过，设备不接受）	
              cardState.push({ state: cardface.status, deviceSn: item.deviceSn, remark: item.remark })
            })
          }
          // 电梯绑定状态 - 人脸
          let faceState = [];
          if (cardface.type == 2) {
            cardface.elevator_list.map(item => {
              // 0是未同步到设备 1是同步成功 2是同步失败（同步过，设备不接受）	
              faceState.push({ state: cardface.status, deviceSn: item.deviceSn, remark: item.remark })
            })
          }

          // 添加的数据
          let data = {
            address: item.address,
            serve_end_time: item.room.serve_end_time,
            remark: cardface.remark,
            deviceSn: deviceSn.toString(),
            card_number: cardface.card ? cardface.card : '',
            card_state: cardState.length == 0 ? '' : JSON.stringify(cardState),
            face_state: faceState.length == 0 ? '' : JSON.stringify(faceState),
            face_path: cardface.face ? cardface.face : ''
          }
          app.call.request('wxapp/addCardFaceAbnormal', data, (res) => {
            app.showTip('异常上报成功');
          })
        }
      }
    })
  },

  // 分享照片
  shareAddFace(e) {
    
    if (e.currentTarget.dataset.isshowaddcardfaceshare == false) {
      app.showTip('已过期或卡槽已满');
      return;
    }

    wx.showModal({
      title: '分享给家人朋友添加照片',
      content: '有效期一小时，确认分享吗？',
      success: (res) => {
        if (res.confirm) {
          let memberRoomId = e.currentTarget.dataset.memberroomid,
            roomId = e.currentTarget.dataset.roomid,
            createTime = new Date().getTime(),
            expirationDate = this.formatDate(createTime + 1 * 1000 * 60 * 60), // 过期时间加1小时
            userId = app.globalData.userInfo.id;
          createTime = this.formatDate(createTime);

          let url = `/pages/cardAndFace/shareAddFace?createTime=${createTime}&expirationDate=${expirationDate}&roomId=${roomId}&memberRoomId=${memberRoomId}&userId=${userId}`;
          wx.navigateTo({ url })
        };
      }
    })
  },
  // 格式化时间 yyyy-MM-dd HH:MM:SS 
  formatDate(times) {
    var date = new Date(times);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
      return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
      return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }
    var second = function () { //获取秒数
      return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },
  // 一键修复 修复当前房号下所以卡片和人脸 重新下发到所有设备
  oneClickRepair(e) {
    wx.showModal({
      title: '提示',
      content: '确认一键修复吗?',
      success: (res) => {
        if (res.confirm) {
          let data = { member_room_id: e.currentTarget.dataset.id }
          app.call.request('wxapp/clickRepair', data, (res) => {
            app.showTip('已下发修复指令,请持续关注卡槽状态');
            this.getCardAndFaceList();
          })
        };
      }
    })
  },
  // 一键查询 查询当前房号下所以卡片和人脸在对应设备中是否绑定
  oneClickSearch(e) {
    wx.showModal({
      title: '提示',
      content: '确认一键查询吗?',
      success: (res) => {
        if (res.confirm) {
          let data = { member_room_id: e.currentTarget.dataset.id }
          app.call.request('wxapp/clickSelect', data, (res) => {
            app.showTip('已下发查询指令,请持续关注卡槽状态');
            this.getCardAndFaceList();
          })
        };
      }
    })
  }
})